<template>
  <page-meta :page-style="'overflow:' + (pageMetaShow ? 'hidden' : 'visible')"></page-meta>
  <PageContainer>
    <view v-if="isToken" class="page">
      <Header
        v-model="headerHeight"
        title=""
        transparent="always"
        :is-go-back="false"
        :z-index="9"
      />
      <view class="user_bg" :style="{ background: getBackground }"></view>
      <view
        class="container"
        :style="{
          minHeight: `calc(100vh - ${headerHeight}px - 100rpx - env(safe-area-inset-bottom))`,
        }"
      >
        <view class="content">
          <UserInfo />
          <view class="container-module">
            <MemberModule />
            <UserBtns />
            <UserBottomList @show-custom-share="handleShowCustomShare" />
          </view>
        </view>
        <TuiFooter :fixed="false" />
      </view>
      <TuiTabbar :current="tabbarList.length - 1" :z-index="9" />
      <PerfectInfoDialog />
    </view>
  </PageContainer>

  <CustomShare
    v-model:visible="customShareVisible"
    :disabled-on-share-app-message="true"
    @register="handleCustomShareRegister"
  />
</template>

<script lang="ts" setup>
  /**  Mine  我的 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import { ref, computed, watch } from 'vue';
  import { onPullDownRefresh, onShareAppMessage } from '@dcloudio/uni-app';
  import { isShareMenu } from '@/utils/is';
  import Header from '@/components/Header/index.vue';
  import UserInfo from './components/userInfo.vue';
  import MemberModule from './components/memberModule.vue';
  import { useUserStore, useUserStoreWithOut } from '@/store/modules/user';
  import UserBtns from './components/userBtns.vue';
  import UserBottomList from './components/userBottomList.vue';
  import { onPageScroll } from '@dcloudio/uni-app';
  import TuiTabbar from '@/components/Tui-tabbar/Tui-tabbar.vue';
  import { ShareButtonId, ShareTypeEnum } from '@/enums/shareEnum';
  import { TabbarPageEnum } from '@/enums/pageEnum';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import TuiFooter from '@/components/Tui-footer/Tui-footer.vue';
  import PerfectInfoDialog from '@/components/PerfectInfoDialog/index.vue';
  import { storeToRefs } from 'pinia';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import { getInviteJoinPosterData, type EmitShowCustomShareType } from './utils';
  import { addAppShareLog } from '@/api';
  import type { PagesType } from '@/router/types/pages';
  import { useAppShare } from '@/hooks/core/useAppShare';

  const { setWxSharePath } = useAppShare();

  const headerHeight = ref(0);
  const { tabbarList, hasShareImgConfig, globalConfig } = useAppStoreWithOut();
  const useUser = useUserStoreWithOut();
  const { isShowPerfectInfoDialog } = storeToRefs(useUser);
  const isToken = computed(() => useUser.token);
  const pageMetaShow = ref(false);

  watch(isShowPerfectInfoDialog, (val) => (pageMetaShow.value = val));

  const customShareVisible = ref(false);
  const [
    register,
    {
      setWxShareOptions,
      setPosterDrawData,
      getCurrentWxShareOptions,
      setShareLogId,
      setButtons,
      setInternalLinkOptions,
    },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      copyLink: true,
      insertOffiaccount: true,
    },
    disableds: {
      shortLink: true,
    },
  });

  async function handleCustomShareRegister(e: any) {
    register(e);
    const { id } = await addAppShareLog({
      path: 'selectiveType',
      query: '',
    });
    setShareLogId(id);
    const posterData = await getInviteJoinPosterData(globalConfig?.posters as string, id);
    await setPosterDrawData([posterData]);
  }

  // onLoad(() => useUser.setUserInfo()); // 用户注册IM
  // onShow(() => isLogin(() => {}, true));

  const getBackground = computed(
    () => `linear-gradient(180deg, ${globalConfig?.themeColor} 0%, #f5f5f5 100%)`,
  );

  // #ifdef MP
  uni.setBackgroundColor({
    backgroundColor: globalConfig?.themeColor,
  });
  // #endif

  const userBtnShareType = ref<EmitShowCustomShareType>();
  async function handleShowCustomShare(type: EmitShowCustomShareType) {
    let pathName: PagesType;
    if (type === 'invite') {
      pathName = 'selectiveType';
      setButtons({
        share: true,
        poster: true,
        copyLink: true,
        insertOffiaccount: true,
      });
      const inviteShare = hasShareImgConfig(ShareTypeEnum.invite);
      await setWxShareOptions([
        {
          path: setWxSharePath({ name: pathName }),
          imageUrl: inviteShare?.iconUrl,
          title: inviteShare?.desc,
        },
      ]);
    } else {
      pathName = 'tencentCode';
      setButtons({
        share: true,
        offiaccount: true,
      });
      const tencentCode = hasShareImgConfig(ShareTypeEnum.tencentCode);
      await setWxShareOptions([
        {
          path: setWxSharePath({ name: pathName }),
          imageUrl: tencentCode?.iconUrl,
          title: tencentCode?.desc,
        },
      ]);
    }
    if (pathName) {
      setInternalLinkOptions({
        name: pathName,
        options: {},
      });
    }
    userBtnShareType.value = type;
    customShareVisible.value = true;
  }

  function getShareData(shareBtnID: string) {
    const membershipShare = hasShareImgConfig(ShareTypeEnum.membership);
    const collectingCard = hasShareImgConfig(ShareTypeEnum.collectingCard);
    const tencentCode = hasShareImgConfig(ShareTypeEnum.tencentCode);
    const inviteShare = getCurrentWxShareOptions();
    const customShareData = {
      path:
        userBtnShareType.value === 'invite'
          ? setWxSharePath({ name: 'selectiveType' })
          : setWxSharePath({ name: 'tencentCode' }),
      imageUrl: userBtnShareType.value === 'invite' ? inviteShare.imageUrl : tencentCode?.iconUrl,
      title: userBtnShareType.value === 'invite' ? inviteShare.title : tencentCode?.desc,
    };
    const data: Recordable = {
      default: {
        path: setWxSharePath({ name: TabbarPageEnum.BASE_MINE }),
        imageUrl: globalConfig?.comShareOptions.shareImg,
      },
      [ShareButtonId.COLLECTINGDATA]: {
        imageUrl: membershipShare?.iconUrl,
        path: setWxSharePath({ name: 'updateMembershipInfo' }),
        title: membershipShare?.desc,
      },
      [ShareButtonId.CUSTOMSHARE_BUTTON_ID]: customShareData,
      // [ShareButtonId.ATTENTION]: {

      // },
      [ShareButtonId.COLLECTINGCARD]: {
        path: setWxSharePath({ name: 'personCard', options: {} }),
        imageUrl: collectingCard?.iconUrl,
        title: collectingCard?.desc,
      },
    };
    return data[shareBtnID];
  }

  onShareAppMessage((e) => {
    return isShareMenu(e.from) ? getShareData('default') : getShareData(e.target.id);
  });

  onPullDownRefresh(async () => {
    await useUser.setUserInfo();
    uni.stopPullDownRefresh();
  });

  onPageScroll((e) => {});
</script>

<style lang="scss" scoped>
  .page {
    background-color: #f5f5f5;
  }
  .user_bg {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1;
    width: 100%;
    height: 460rpx;
  }

  .container {
    position: relative;
    z-index: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .container-module {
      padding: 0 30rpx;
      margin-top: 40rpx;
    }
  }
</style>
